﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if !SILVERLIGHT
using System.Xaml;
#else
using System.Windows.Markup;
#endif

namespace UIT
{
	class UitXamlReader : XamlReader
	{
		private XamlReader reader;
		private string[] namespacesToIgnore;
		List<string> prefixesToIgnore;
		public UitXamlReader(XamlReader reader, params string[] namespacesToIgnore)
		{
			this.namespacesToIgnore = namespacesToIgnore;
			prefixesToIgnore = new List<string>();
			this.reader = reader;
		}

		public override bool IsEof
		{
			get { return reader.IsEof; }
		}

		public override XamlMember Member
		{
			get { return reader.Member; }
		}

		public override NamespaceDeclaration Namespace
		{
			get { return reader.Namespace; }
		}

		public override XamlNodeType NodeType
		{
			get { return reader.NodeType; }
		}

		public override bool Read()
		{
			return SkipIgnoredNodes(reader.Read());
		}

		public bool SkipIgnoredNodes(bool result)
		{
			if (NodeType == XamlNodeType.NamespaceDeclaration && namespacesToIgnore.Any(ns => ns == Namespace.Namespace))
			{
				//Skip this
				return Read();
			}
			if (NodeType == XamlNodeType.StartMember && namespacesToIgnore.Any(ns => ns == Member.PreferredXamlNamespace))
			{
				//Skip this
				reader.Read();
				//SKip Value
				reader.Read();
				//Skip End
				return Read();
			}
			if (NodeType == XamlNodeType.StartObject)
				if (namespacesToIgnore.Any(ns => ns == this.Type.PreferredXamlNamespace))
				{
					int i = 0;
					do
					{
						if (NodeType == XamlNodeType.StartObject || NodeType==XamlNodeType.GetObject)
							i++;
						if (NodeType == XamlNodeType.EndObject)
							i--;
						reader.Read();
					}
					while (i > 0);
					return SkipIgnoredNodes(result);
				}
				else
				{
				}
			return result;
		}

		public override XamlSchemaContext SchemaContext
		{
			get { return reader.SchemaContext; }
		}

		public override XamlType Type
		{
			get { return reader.Type; }
		}

		public override object Value
		{
			get { return reader.Value; }
		}
	}
}
